package com.example.librarymanagement.security;

import com.example.librarymanagement.exception.CaptchaException;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.util.Const;
import com.example.librarymanagement.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author fgba
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();

        if ("/library/login".equals(uri) && "POST".equals(request.getMethod())) {
            log.info("获取到login链接，正在校验验证码 -- " + uri);
            try {
                validate(request);
            } catch (CaptchaException e) {
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String token = request.getParameter("token");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
            throw new CaptchaException(ResultCode.VERIFICATION_IS_NULL);
        }
        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, token))) {
            throw new CaptchaException(ResultCode.VERIFICATION_CODE_ERROR);
        }
        redisUtil.hdel(Const.CAPTCHA_KEY, token);
    }
}
